package br.com.sadim.web.filter;


import javax.servlet.*;

import org.hibernate.SessionFactory;

import br.com.sadim.util.HibernateUtil;

public class HibernateSessionRequestFilter implements Filter {
	private SessionFactory sf;
	 
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
            throws ServletException {
 
        try {
            sf.getCurrentSession().beginTransaction();
 
            // Call the next filter (continue request processing)
            chain.doFilter(request, response);
 
            // Commit and cleanup
            sf.getCurrentSession().getTransaction().commit();
            sf.getCurrentSession().close();
 
        } catch (Throwable e) {
        	try {
        		if(sf.getCurrentSession().getTransaction().isActive()) {
        			sf.getCurrentSession().getTransaction().rollback();
        		}
        	} catch (Throwable ex ) {
        		ex.printStackTrace();
        	}
        	throw new ServletException(e);
        }
    }
 
    public void init(FilterConfig filterConfig) throws ServletException {
        sf = HibernateUtil.getSessionFactory();
    }
 
    public void destroy() {}
}
